package com.suse.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.suse.constant.RedisConstant;
import com.suse.entity.ShopType;
import com.suse.mapper.ShopTypeMapper;
import com.suse.result.Result;
import com.suse.service.ShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.suse.common.util.core.StringUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.suse.result.ResultEnum.RESULT_SHOP_TYPE_NOT_FOUND;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 辜玉彬
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements ShopTypeService {

    private final StringRedisTemplate redisTemplate;

    public ShopTypeServiceImpl(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public Result getShopTypeList() throws JsonProcessingException {
        // 1.从 redis 中查询数据
        String shopTypeListJson = redisTemplate.opsForValue().get(RedisConstant.SHOP_TYPE_LIST);
        // 2.判断数据是否存在
        if (StringUtil.isNotEmpty(shopTypeListJson)) {
            // SpringMVC 的 Bug ?????????????????????
            List<ShopType> typeList = objectMapper.readValue(shopTypeListJson, new TypeReference<List<ShopType>>() {});
            // 3.存在，直接返回数据
            return Result.success(typeList);
        }
        // 4.不存在，从 mysql 中查询数据
        List<ShopType> typeList = query().orderByAsc("sort").list();
        // 5.判断数据是否存在
        if (CollectionUtil.isEmpty(typeList)) {
            // 6.不存在，返回错误信息
            return Result.error(RESULT_SHOP_TYPE_NOT_FOUND);
        }
        // 7.存在，将数据保存到 redis 中
        redisTemplate.opsForValue().set(RedisConstant.SHOP_TYPE_LIST,objectMapper.writeValueAsString(typeList), RedisConstant.SHOP_TYPE_LIST_TTL, TimeUnit.MINUTES);
        // 8.返回数据
        return Result.success(typeList);
    }

}
